
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:gun/http/api.dart';
import 'package:gun/page/position_page.dart';
import 'package:gun/util/toast_util.dart';
import '../entity/book_entity.dart';
import '../main.dart';
import '../widget/dialog.dart';

class Query extends StatefulWidget {
  const Query({Key? key}) : super(key: key);

  @override
  State<Query> createState() => _QueryState();
}

class _QueryState extends State<Query> {

  RxList<BookEntity> bookList = RxList();
  var _keyword = '';
  var page = 1;
  var limit = 10;

  final ScrollController _scrollController = ScrollController();

  @override
  initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        page++;
        _loadMore();
      }
    });
    player.play('audio/keyword.mp3');
  }

  _loadMore() async {
    var list = await query(_keyword, page, limit);
    if(list != null){
      if(page == 1){
        bookList.clear();
      }
      bookList.addAll(list);
    }else{
      if(page == 1){
        bookList.clear();
      }
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  _title(){
    return Container(
        margin: EdgeInsets.only(top: 30.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            InkWell(
              onTap: (){
                Get.back();
              },
              child: Row(
                children: [
                  const Icon(Icons.arrow_back_ios_new,color: Colors.white,),
                  Text("返回",style: TextStyle(color: Colors.white,fontSize: 16.sp),)
                ],
              )
            ),
            Image.asset("assets/images/query_title.png",width: 100.w,fit: BoxFit.fitWidth,),
            InkWell(
              onTap: (){
                DialogWidget().settingDialog();
              },
              child: Text("调整功率",style: TextStyle(color: Colors.white,fontSize: 16.sp),),
            )
          ],
        )
    );
  }


  _list(){
    return Obx(() => SizedBox(
      height: 450.h,
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _listItem(index);
        },
        itemCount: bookList.length,
        controller: _scrollController,
      )
    ));
  }

  _listItem(index){
    var item = bookList[index];
    return Container(
      margin: EdgeInsets.only(top: 10.r),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(6.r)),
      ),
      padding: EdgeInsets.all(10.r),
      child: Column(
        children: [
          InkWell(
            onTap: (){
              var index = bookList.indexOf(item);
              bookList.removeAt(index);
              item.expand = !item.expand;
              bookList.insert(index, item);
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                SizedBox(width: 230.w,child:Text('${item.mainTitle}'),),
                InkWell(
                  onTap: (){
                    Get.to(()=>const Position(),arguments: item);
                  },
                  child: Image.asset("assets/images/position.png",width: 50.w,fit: BoxFit.fitWidth,),
                ),
                Icon(item.expand?Icons.keyboard_arrow_up_rounded:Icons.keyboard_arrow_down_rounded,color: Colors.grey,)
              ],
            ),
          ),
          if(item.expand)...
            [
              Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  SizedBox(height: 6.h,),
                  Divider(height: 0.5.h, indent: 4.w, endIndent: 4.w, color: const Color.fromRGBO(86, 169, 255, 1),),
                  SizedBox(height: 6.h,),
                  Row(
                    children: [
                      const Text('存放位置：'),
                      Text('${item.placeName}',style: const TextStyle(color: Color.fromARGB(255, 20, 196, 196)),),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text('条码号：${item.no}'),
                      Text('索书号：${item.searchNo}'),
                    ],
                  )
                ],
              )
            ]
        ],
      )
    );
  }

  _searchBarWidget(){
    return Container(
        width: 360.w,
        decoration:BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(6.r)),
        ),
        padding: EdgeInsets.only(left:10.r),
        margin:  EdgeInsets.only(bottom: 10.r,top: 10.r),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Icon(Icons.search,color: Colors.black,),
            SizedBox(
              width: 250.w,
              child: TextField(
                minLines: 1,
                textInputAction: TextInputAction.search,
                onChanged: (input){
                  _keyword = input;
                },
                decoration: InputDecoration(
                    contentPadding: EdgeInsets.only(top: 10.r,bottom: 10.r),
                    isCollapsed: true,
                    hintText: "可根据 条码号、书名、索书号搜索",
                    border: InputBorder.none,
                    hintStyle: TextStyle(color: Colors.black,fontSize: 14.sp)
                ),
                style: TextStyle(color: Colors.black,fontSize: 14.sp),
              ),

            ),
            Container(
              width: 70.w,
              height: 40.h,
              decoration:BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.only(topRight:Radius.circular(6.r),bottomRight: Radius.circular(6.r)),
              ),
              alignment: Alignment.center,
              child: InkWell(
                onTap: () async {
                  if(_keyword.isEmpty){
                    toastWarn('内容不能为空');
                    return;
                  }
                  page = 1;
                  _loadMore();
                },
                child: const Text('查找',style: TextStyle(color: Colors.white),),
              )
            )
          ],
        )
    );
  }


  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: Container(
            width: double.infinity,
            height: double.infinity,
            padding: EdgeInsets.only(left: 20.r,right: 20.r),
            decoration: const BoxDecoration(
              image: DecorationImage(
                fit: BoxFit.fill,
                image: AssetImage(
                  "assets/images/bg.png",
                ),
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                _title(),
                SizedBox(height: 30.h,),
                _searchBarWidget(),
                Obx(() => bookList.isEmpty?
                  Container(
                    width: double.infinity,
                    height: 500.h,
                    alignment: Alignment.center,
                    child: Image.asset("assets/images/empty.png",),
                  ) :_list()
                ),
              ],
            )
        ),
      ),
    );
  }
}